/* $Id: ObjectTypeCustomizer.java,v 1.2 2003/08/02 19:20:02 survey Exp $
 * 
 *                 Sun Public License Notice
 *
 * The contents of this file are subject to the Sun Public License
 * Version 1.0 (the "License"). You may not use this file except in
 * compliance with the License. A copy of the License is available at
 * http://www.sun.com/
 *
 * The Original Code is NetBeans. The Initial Developer of the Original
 * Code is Sun Microsystems, Inc. Portions Copyright 1997-2000 Sun
 * Microsystems, Inc. All Rights Reserved.
 */


package org.medbeans.modules.search.types;


import java.beans.Customizer;
import java.beans.PropertyChangeListener;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Vector;
import java.util.TreeSet;
import java.util.Enumeration;
import javax.swing.border.CompoundBorder;
import javax.swing.border.TitledBorder;
//import javax.swing.JFrame;
import javax.swing.JPanel;

import org.openide.loaders.DataLoader;
import org.openide.TopManager;
import org.openide.util.NbBundle;


/**
 * Customizer of <code>ObjectTypeType</code> bean.
 *
 * @author  Petr Kuzel
 */
public class ObjectTypeCustomizer extends JPanel implements Customizer {

    /** Object to customize. */
    private ObjectTypeType peer;
    
    /** Flag indicating the are setting of object in run. */
    private boolean setting = false;

    
    /** Creates new form <code>ObjectTextCustomizer</code>. */
    public ObjectTypeCustomizer() {
        initComponents ();
        initAccessibility();
        TitledBorder tb = new TitledBorder(NbBundle.getBundle(ObjectTypeCustomizer.class).getString("TEXT_LABEL_OBJECT_TYPE"));
        
        tb.setBorder(new CompoundBorder());
        setBorder (tb);
    }

    private void initAccessibility() {
        this.getAccessibleContext().setAccessibleDescription(NbBundle.getBundle(ObjectTypeCustomizer.class).getString("TEXT_LABEL_OBJECT_TYPE"));
        typeList.getAccessibleContext().setAccessibleName(NbBundle.getBundle(ObjectTypeCustomizer.class).getString("ACSN_TypeList"));
        typeList.getAccessibleContext().setAccessibleDescription(NbBundle.getBundle(ObjectTypeCustomizer.class).getString("ACSD_TypeList"));
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the FormEditor.
     */
    private void initComponents() {//GEN-BEGIN:initComponents
        java.awt.GridBagConstraints gridBagConstraints;

        jScrollPane1 = new javax.swing.JScrollPane();
        typeList = new javax.swing.JList();

        setLayout(new java.awt.GridBagLayout());

        typeList.addListSelectionListener(new javax.swing.event.ListSelectionListener() {
            public void valueChanged(javax.swing.event.ListSelectionEvent evt) {
                typeListValueChanged(evt);
            }
        });

        jScrollPane1.setViewportView(typeList);

        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
        gridBagConstraints.weightx = 1.0;
        gridBagConstraints.weighty = 1.0;
        gridBagConstraints.insets = new java.awt.Insets(4, 4, 4, 4);
        add(jScrollPane1, gridBagConstraints);

    }//GEN-END:initComponents

    private void typeListValueChanged (javax.swing.event.ListSelectionEvent evt) {//GEN-FIRST:event_typeListValueChanged
        if(setting) 
            // ignore calls caused by setObject() implementation
            return; 

        DataLoader lds[] = TopManager.getDefault().getLoaderPool().toArray();

        Vector toret = new Vector();
        Object[] sel = typeList.getSelectedValues();

        for (int i=0; i<lds.length; i++) {
            String id = lds[i].getDisplayName();
            if (id == null) continue; //may be null :-(
            for (int j=0; j<sel.length; j++) {
                if (sel[j] == null) continue; //may be null :-(
                if (id.equals((String)sel[j])) {
                    toret.add(lds[i]);
                    break;
                }
            }
        }

        Class[] ret =  new Class[toret.size()];

        Iterator it = toret.iterator();
        int k = 0;
        while (it.hasNext()) {
            ret[k++] = it.next().getClass();
        }

        peer.setMask(ret);
    }//GEN-LAST:event_typeListValueChanged


    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JList typeList;
    private javax.swing.JScrollPane jScrollPane1;
    // End of variables declaration//GEN-END:variables

    /** Sets object to customize. Initialize customizer with proper values. 
     * Implements <code>Customizer</code> inetrface method.
     * @param obj object t customize */
    public void setObject(Object obj) {
        setting = true;

        try {
            peer = (ObjectTypeType)obj;

            Enumeration en = TopManager.getDefault().getLoaderPool().allLoaders();

            // Model data for list.
            TreeSet types = new TreeSet();

            ArrayList selected = new ArrayList();

            while ( en.hasMoreElements() ) {
                DataLoader nextLoader = (DataLoader) en.nextElement();

                String displayName = nextLoader.getDisplayName();
                if (displayName == null) 
                    continue;
                
                types.add(displayName);
                
                Class[] mask = peer.getMask();
                
                // Create indices of values to select.
                if(mask == null) 
                    continue;

                Class repreClass = nextLoader.getRepresentationClass();
                if(repreClass == null)
                    continue;
                
                for(int j = 0; j < mask.length; j++) {
                    DataLoader loader = DataLoader.getLoader(mask[j]);
                    if(loader != null && repreClass.equals(loader.getRepresentationClass())) {
                        selected.add(displayName);
                        break; 
                    }
                }
            }

            // select saved values
            typeList.setListData((String[])types.toArray(new String[types.size()]));

            int[] indexes = new int[selected.size()];
            
            ArrayList typesList = new ArrayList(types);

            for(int i = 0; i < indexes.length; i++) {
                indexes[i] = typesList.indexOf(selected.get(i));
            }

            typeList.setSelectedIndices(indexes);

        } catch(Exception e) {
            if(Boolean.getBoolean("netbeans.debug.exceptions")) // NOI18N
                e.printStackTrace();
        } finally {
            setting = false;
        }

    }

    /** Dummy implementation of <code>Customizer</code> interface method. */
    public void addPropertyChangeListener(PropertyChangeListener p1) {}

    /** Dummy implementation of <code>Customizer</code> interface method. */
    public void removePropertyChangeListener(PropertyChangeListener p1) {}

    /** Overrides superclass method. Requests ffocus si delegated to typeList component. */
    public void requestFocus() {
        typeList.requestFocus();
    }

    
}
